import { message } from 'antd';
import { isEmpty, findIndex } from 'lodash';
import StorageManager from '@/utils/StorageManager';

const subName = (useRuleTypeName: string) => {
  if (useRuleTypeName) {
    const index = useRuleTypeName.indexOf('-');
    return useRuleTypeName.substring(0, index);
  }
  return '';
};

// 详情回显
const convertValueForDetail = (value: Partial<API.RealProfileInfo>) => {
  // 数量和限制关系
  value.countCheck = value.count === -1 ? ['不限制'] : [];
  value.personLimitCountCheck = value.personLimitCount === -1 ? ['不限制'] : [];
  value.reusableCountCheck = value.reusableCount === -1 ? ['不限制'] : [];
  // 所有多选拉下 ''改为[]
  value.filterTags = value.filterTags ? value.filterTags.split(',') : [];
  value.regionNames = value.regionNames ? value.regionNames.split(',') : [];
  value.queryChannelId = value.queryChannelId ? value.queryChannelId.split(',') : [];
  value.useChannelId = value.useChannelId ? value.useChannelId.split(',') : [];
  value.useTabs = value.useTabs ? value.useTabs.split(',') : [];
  // 限制使用规则明细
  value.useMarketing = value.useMarketings ? value.useMarketings : [];
  value.useMarketingMore = [];
  value.dweekLimitValue = value.dweekLimitValue ? value.dweekLimitValue.split(',') : [];
  value.dmonthLimitValue = value.dmonthLimitValue ? value.dmonthLimitValue.split(',') : [];
  value.notifyRuleNames = value.notifyRuleNames ? value.notifyRuleNames.split(',') : [];
  value.crossBrands = value.crossBrands ? value.crossBrands.split(',') : [];
  value.bookChannelIds = value.bookChannelIds ? value.bookChannelIds.split(',') : [];
  value.tapChannelIds = value.tapChannelIds ? value.tapChannelIds.split(',') : [];
  value.storeTypeIds = value.storeTypeIds ? value.storeTypeIds.split(',') : [];
  value.scenarioIds = value.scenarioIds ? value.scenarioIds.split(',') : [];
  value.daypartids = value.daypartids ? value.daypartids.split(',') : [];
  //   限制使用高级明细--特殊处理
  const eunmList: any = StorageManager.getLocalStorageSync('eunmList');
  const OptionsUsemarketingMore = eunmList?.OptionsUsemarketingMore || [];
  OptionsUsemarketingMore.forEach((item: any) => {
    if (value.useMarketing.includes(item.value)) {
      value.useMarketingMore.push(item.value);
    }
  });
  const arrUseMarketing: any = [];
  value.useMarketing.forEach((item: any) => {
    const index = findIndex(OptionsUsemarketingMore, function (o: any) {
      return o.value == item;
    });
    if (index === -1) {
      arrUseMarketing.push(item);
    }
  });
  value.useMarketing = arrUseMarketing;

  // if (value.useMarketing.includes('CATEB')) {
  //   value.useMarketingMore = ['CATEB'];
  //   value.useMarketing = value.useMarketing.filter(
  //     (useMarketItem: any) => !OptionsUsemarketingMore.includes(useMarketItem),
  //   );
  // } else {
  //   value.useMarketingMore = [];
  // }

  //   16-指定外送费--deliveryFeeList处理
  if (value.useRuleTypeName && value.useRuleTypeName === '16-指定外送费') {
    const deliveryFeeListBro = [];
    //ex:[1000-1400]->800,[1500-2130]->900...
    if (value.productId) {
      const list = value.productId.split(','); // ['->800','[1000-1400]->800']
      const listRule = value.productIdRule.split(','); // ['->800','[1000-1400]->800']
      for (let i = 0; i < list.length; i++) {
        const listItem = list[i].split('->'); // ['[]',800]
        const listItemRule = listRule[i].split('->'); // ['[]',800]
        if (listItem.length > 1) {
          const time = listItem[0].replace('[', '').replace(']', ''); // 1000-1400
          //   const timeRule = listItemRule[0].replace('[', '').replace(']', ''); // 1000-1400
          deliveryFeeListBro.push({
            timeRange: time || '',
            startPoint: listItemRule[1] || '',
            deliveryFee: listItem[1] || '',
          });
        }
      }
      deliveryFeeListBro.push({
        timeRange: '',
        startPoint: '',
        deliveryFee: '',
      });
      value.deliveryFeeList = deliveryFeeListBro;
    } else {
      value.deliveryFeeList = [
        {
          timeRange: '',
          startPoint: '',
          deliveryFee: '',
        },
      ];
    }
  }
  // 回显  tenantList  将 productIdEx、productIdRuleEx、productIdBackupEx转化为object
  value.productIdEx = !isEmpty(value.productIdEx) ? JSON.parse(value.productIdEx) : '';
  value.productIdRuleEx = !isEmpty(value.productIdRuleEx) ? JSON.parse(value.productIdRuleEx) : '';
  value.productIdBackupEx = !isEmpty(value.productIdBackupEx)
    ? JSON.parse(value.productIdBackupEx)
    : '';

  // 活动时间--范围--回显
  value.activityDateRange = [value.activityStartTime, value.activityEndTime];

  return value;
};

// 保存之前处理字段
const convertValueForSave = (
  value: Partial<API.RealProfileInfo>, //  model 中的 formValue
  formRefValue: Partial<API.RealProfileInfo>, //  表单自己的  formValue
) => {
  // 所有多选拉下 []改为''
  value.filterTags = value.filterTags ? value.filterTags.join(',') : '';
  value.regionNames = value.regionNames ? value.regionNames.join(',') : '';
  value.queryChannelId = value.queryChannelId ? value.queryChannelId.join(',') : '';
  value.useChannelId = value.useChannelId ? value.useChannelId.join(',') : '';
  value.useTabs = value.useTabs ? value.useTabs.join(',') : '';
  value.useMarketing = value.useMarketing ? value.useMarketing.join(',') : '';
  value.useMarketingMore = value.useMarketingMore ? value.useMarketingMore.join(',') : '';
  value.dweekLimitValue = value.dweekLimitValue ? value.dweekLimitValue.join(',') : '';
  value.dmonthLimitValue = value.dmonthLimitValue ? value.dmonthLimitValue.join(',') : '';
  value.notifyRuleNames = value.notifyRuleNames ? value.notifyRuleNames.join(',') : '';
  value.crossBrands = value.crossBrands ? value.crossBrands.join(',') : '';
  value.bookChannelIds = value.bookChannelIds ? value.bookChannelIds.join(',') : '';
  value.tapChannelIds = value.tapChannelIds ? value.tapChannelIds.join(',') : '';
  value.storeTypeIds = value.storeTypeIds ? value.storeTypeIds.join(',') : '';
  value.scenarioIds = value.scenarioIds ? value.scenarioIds.join(',') : '';
  value.daypartids = value.daypartids ? value.daypartids.join(',') : '';

  //   16-指定外送费--deliveryFeeList处理
  if (value.useRuleTypeName && value.useRuleTypeName === '16-指定外送费') {
    let param = '';
    let paramRule = '';
    if (value.deliveryFeeList && value.deliveryFeeList.length > 0) {
      value.deliveryFeeList.forEach((item: any, index: number) => {
        if (item.deliveryFee && item.timeRange) {
          const single = '[' + item.timeRange + ']' + '->' + item.deliveryFee;
          const singleRule = '[' + item.timeRange + ']' + '->' + item.startPoint;
          param = param + single;
          paramRule = paramRule + singleRule;
          if (index < value.deliveryFeeList.length - 1) {
            param = param + ',';
            paramRule = paramRule + ',';
          }
        }
      });
    }
    value.productId = param;
    value.productIdRule = paramRule;
  }

  // 根据 tenantFather  tenantList  将 productIdEx、productIdRuleEx、productIdBackupEx转化为json
  if (value.tenantList && value.tenantList.length > 0) {
    const productIdExBro = {};
    const productIdRuleExBro = {};
    const productIdBackupExBro = {};
    value.tenantList.forEach((item: string) => {
      if (formRefValue.productIdEx && formRefValue.productIdEx[item]) {
        productIdExBro[item] = formRefValue.productIdEx[item];
      }
      if (formRefValue.productIdRuleEx && formRefValue.productIdRuleEx[item]) {
        productIdRuleExBro[item] = formRefValue.productIdRuleEx[item];
      }
      if (formRefValue.productIdBackupEx && formRefValue.productIdBackupEx[item]) {
        productIdBackupExBro[item] = formRefValue.productIdBackupEx[item];
      }
    });
    // productIdEx、productIdRuleEx、productIdBackupEx
    value.productIdEx = !isEmpty(productIdExBro) ? JSON.stringify(productIdExBro) : '';
    value.productIdRuleEx = !isEmpty(productIdRuleExBro) ? JSON.stringify(productIdRuleExBro) : '';
    value.productIdBackupEx = !isEmpty(productIdBackupExBro)
      ? JSON.stringify(productIdBackupExBro)
      : '';
  } else {
    value.tenantList = [value.tenantFather];
  }

  // 隐藏表单数据落库
  if (Number(value.crossBrandPlace) === 0) {
    // 是否跨品牌发放,“发放品牌”；“同步品牌”；“多品牌卡包活动号”；非空
    value.placeBrand = '';
    value.crossBrands = '';
    value.crossActivity = '';
  }
  if (Number(value.crossBrandPlace) === 1) {
    value.crossActivity = '';
  }
  if (Number(value.crossBrandPlace) === 2) {
    value.placeBrand = '';
    value.crossBrands = '';
  }
  // 是否生成预约券 “预约券活动id”；“预加载渠道号”；“预加载缓存时间（秒）”；非空
  if (Number(value.needBookCoupon) === 0) {
    value.bookActivityIds = '';
    value.preloadChannelId = '';
    value.preloadSeconds = '';
  }
  // 门店限制
  if (value.useMarketing.indexOf('STORELIMIT') === -1) {
    value.storegroup = '';
    value.storeLimit = '';
    value.storeValues = '';
  }
  // 日期限制
  if (value.useMarketing.indexOf('DATELIMIT') === -1) {
    value.dateGroup = '';
    value.dateLimit = '';
    value.dateLimitValue = '';
  }
  // 时间限制
  if (value.useMarketing.indexOf('TIMELIMIT') === -1) {
    value.timeLimit = '';
    value.timeLimitValue = '';
  }
  // 星期限制
  if (value.useMarketing.indexOf('DWEEKLIMIT') === -1) {
    value.dweekLimit = '';
    value.dweekLimitValue = '';
  }
  // 天数限制
  if (value.useMarketing.indexOf('DMONTHLIMIT') === -1) {
    value.dmonthLimit = '';
    value.dmonthLimitValue = '';
  }
  // 使用次数限制
  if (value.useMarketing.indexOf('REUSABLECOUNTLIMIT') === -1) {
    value.reusableType = '';
    value.reusableCountValue = '';
  }
  // 有效期模式
  if ([1, 2].includes(value.validThruRule)) {
    value.delayDays = '';
    value.activationDays = '';
  }
  // 使用规则类型
  if (
    !['01', '03', '05', '07', '08', '09', '10', '12', '13', '17', '201'].includes(
      subName(value.useRuleTypeName),
    )
  ) {
    value.priceRule = ''; // 满
  }
  if (
    !['01', '03', '05', '07', '08', '09', '10', '12', '13', '17', '201'].includes(
      subName(value.useRuleTypeName),
    ) &&
    !['01', '03', '08', '13', '17', '201'].includes(subName(value.useRuleTypeName))
  ) {
    value.returnAmount = ''; // 减 POS结算总额
  }
  if (
    !['06', '07', '09'].includes(subName(value.useRuleTypeName)) &&
    !['14', '15', '18'].includes(subName(value.useRuleTypeName))
  ) {
    value.discountPrice = ''; // 优惠购买价格 减免上限金额
  }
  if (!['04', '05', '10', '12', '14', '15', '18'].includes(subName(value.useRuleTypeName))) {
    value.returnDiscount = ''; // POS结算折扣比例
  }
  // 是否延期券
  if (Number(value.isExpanded) === 0) {
    value.expandedStartDays = '';
    value.expandedDays = '';
  }

  return value;
};

// 保存前---提示校验value
const beforeSaveValidate = (value: Partial<API.RealProfileInfo>) => {
  if (isEmpty(value.activityStartTime)) {
    message.warning('活动开始时间不得为空！');
    return false;
  }
  if (isEmpty(value.activityEndTime)) {
    message.warning('活动结束时间不得为空！');
    return false;
  }

  // 限制使用规则明细--非空--校验开始
  if (value.useMarketing && value.useMarketing.length > 0) {
    if (value.useMarketing.includes('STORELIMIT') && !value.storegroup && !value.storeValues) {
      message.warning('门店列表和餐厅组需要填写一个，不能全为空！');
      return false;
    }
    if (value.useMarketing.includes('DATELIMIT') && !value.dateGroup && !value.dateLimitValue) {
      message.warning('日期区间和日期组需要填写一个，不能全为空！');
      return false;
    }
    if (value.useMarketing.includes('TIMELIMIT') && !value.timeLimitValue) {
      message.warning('时间区间不能为空！');
      return false;
    }
    if (value.useMarketing.includes('DWEEKLIMIT') && value.dweekLimitValue.length === 0) {
      message.warning('星期限制不能为空！');
      return false;
    }
    if (value.useMarketing.includes('DMONTHLIMIT') && value.dmonthLimitValue.length === 0) {
      message.warning('天数限制不能为空！');
      return false;
    }
    if (
      value.useMarketing.includes('REUSABLECOUNTLIMIT') &&
      value.reusableType &&
      value.reusableType === '1' &&
      !value.reusableCountValue
    ) {
      message.warning('使用次数不能为空！');
      return false;
    }
    if (value.useMarketing.includes('CONDIMENTW') && value.useMarketing.includes('CONDIMENTB')) {
      message.warning('只能选择【适用于配料】或者【优惠不适用于配料】其中一项');
      return false;
    }
    // if (
    //   value.salesType &&
    //   value.salesType !== 1 &&
    //   value.tenderTypeDesc &&
    //   ['折扣', '结账+折扣'].includes(value.tenderTypeDesc) &&
    //   value.sales &&
    //   Number(value.sales) <= 0
    // ) {
    //   message.error('券净值必须大于0');
    //   return false;
    // }
    if (
      value.salesType &&
      value.salesType === 4 &&
      value.internalCouponPrice &&
      Number(value.internalCouponPrice) <= 0
    ) {
      message.warning('内部结算价格必须大于0');
      return false;
    }
    if (
      value.salesType &&
      value.salesType === 0 &&
      value.placeStyle &&
      value.placeStyle === '现金购买'
    ) {
      message.warning('发放性质选现金购买时，SalesType不能为0');
      return false;
    }
    if (
      value.businessModel &&
      value.businessModel.indexOf('B2C') !== -1 &&
      value.invoiceType &&
      value.invoiceType === '买断'
    ) {
      message.warning('业务模式选择B2C时，开票节点不能为买断');
      return false;
    }
    if (value.salesType && value.salesType === 1 && value.sales && Number(value.sales) <= 0) {
      message.warning('Sales计算方式选择1，Sales不能小于或等于0');
      return false;
    }
    if (
      value.placeStyle &&
      value.placeStyle === '现金购买' &&
      value.salesType &&
      value.salesType === 3 &&
      ((value.sales && Number(value.sales) <= 0) ||
        (value.couponPrice && Number(value.couponPrice) <= 0))
    ) {
      message.warning('发放性质为现金购买时，劵净值必须大于0，商城净值必须大于0');
      return false;
    }
  }
  return true;
};

export { beforeSaveValidate, convertValueForSave, convertValueForDetail };
